/**
 * @module ChiVoxSDK/html5
 * @author Don Li <kai.li@chivox.com>
 * @licence
 * Copyright (c) 2017 - 2020 ChiVox Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import Utils from '../utils';
import cfg from '../config.json';

let __inited = false;

/**
 * HTML5模式下的波形图。
 *
 * 基于Canvas绘制。
 */
class VolumeBar {
    /**
     * 绘制一个波形图。(如果已绘制过，不会再次绘制）。
     *
     * param {string} recorder_id - 要绘制在当前页面的DOM节点的ID。
     * param {AudioContext} audioCtx - 获取到的页面音频设备上下文。
     * param {Analysis} analyser - 获取到的页面音频数据解析器。
     * param {Object} mic - 获取到的页面音频麦克风设备。
     */
    constructor(recorder_id, audioCtx, analyser, mic) {
        this.__ele = Utils.find(document, recorder_id);
        if (!this.__ele) return;

        this.__audioCtx = audioCtx;
        this.__analyser = analyser;
        this.__mic      = mic;

        if (!__inited) {
            __inited = true;

            this.__bar = document.createElement('canvas');
            this.__ele.appendChild(this.__bar);
        } else {
            this.__bar = Utils.find(this.__ele, 'canvas');
        }

        this.show();
    }

    /** 显示波形图 */
    show() {
        if (this.__shown) return;
        this.__shown = true;
        var mic      = this.__mic;
        var analyser = this.__analyser;
        var audioCtx = this.__audioCtx;
        var cv       = this.__bar;

        cv.width     = this.__ele.width > 0 ? this.__ele.width : 175;
        cv.height    = this.__ele.height > 0 ? this.__ele.height : 50;

        var ctx  = cv.getContext('2d');
        var W    = cv.width;
        var H    = cv.height;
        var STEP = 1;
        var N    = W / STEP;

        var energies = new Array();

        ctx.strokeStyle = "#6CA6CD";
        cv.border = 1;
        cv.style.backgroundColor = "#CBCBCB";

        let draw = () => {
            ctx.clearRect(0, 0, W, H);

            ctx.beginPath();
            ctx.moveTo(0.5, Math.floor(H * 0.9) + 0.5);
            ctx.lineTo(W - 0.5, Math.floor(H * 0.9) + 0.5);
            ctx.closePath();
            ctx.lineWidth = 1;
            ctx.strokeStyle = "rgba(255, 0, 0, 0.5)";
            ctx.stroke();

            ctx.strokeStyle = "#6CA6CD";
            var dataArray = new Uint8Array(analyser.frequencyBinCount);
            analyser.getByteFrequencyData(dataArray);

            for (var i = 0; i < analyser.frequencyBinCount; i += analyser.frequencyBinCount / 3) {
                if (energies.length >= N) energies.shift();
                energies.push(dataArray[i]);
            }

            ctx.beginPath();
            for (var j = 0; j < N; j++) {
                var energy = energies[j] * 1.2;
                ctx.moveTo(STEP * j, H);
                ctx.lineTo(STEP * j, H - H * energy / 256);
                ctx.stroke();
            }

            setTimeout(draw, 150);
        };

        draw();
    }
}

export default VolumeBar
